#include "BlockQueue.hpp"
#include "Task.hpp"

static const size_t C_NUM = 5;
static const size_t P_NUM = 5;

void* Consumer(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    while(true) {
        Task t = bq->pop();
        t.Run();
        printf("线程: %p, 消费者获得数据: %s, 运算结果是: %s\n", pthread_self(), t.GetTask().c_str(), t.GetResult().c_str());
        // sleep(1);
    }
    
}

void* Producer(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    int x = 0, y = 0;
    char op = ' ';
    while(true) {
        x = rand() % 100;     // [0, 99]
        y = rand() % 100;     // [0, 99]
        op = opStr[rand() % 4];
        Task t(x, y, op);
        usleep(10);              // 模拟获取数据需要时间
        bq->push(t);
        printf("线程: %p, 生产者生产了一个任务:%s\n", pthread_self() ,t.GetTask().c_str());
        // sleep(1);
    }
}

int main()
{
    srand((unsigned int)time(nullptr));
    BlockQueue<Task>* bq = new BlockQueue<Task>();
    pthread_t c[C_NUM], p[P_NUM];
    for(size_t i = 0; i < P_NUM;++i)
        pthread_create(c+i, nullptr, Producer, bq);
    for(size_t i = 0; i < C_NUM;++i)
    pthread_create(p+i, nullptr, Consumer, bq);

    for(size_t i = 0; i < P_NUM;++i)
        pthread_join(c[i], nullptr);
    for(size_t i = 0; i < C_NUM;++i)
        pthread_join(p[i], nullptr);
    delete bq;
    return 0;
}